package com.ledim.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.ledim.activity.base.LeDimBaseActivity;
import com.ledim.app.LeDimApplication;
import com.ledim.bean.LoginResponseBean;
import com.ledim.bean.base.BaseResultInfo;
import com.ledim.service.ApiService;
import com.ledim.service.LedimApiServiceFactory;
import com.ledim.service.LedimHttpObserver;
import com.ledim.utils.LedimBaseUtils;
import com.ledim.utils.LedimFunctionUtils;
import com.ledim.utils.LedimNetWorkUtils;
import com.ledim.utils.LedimSpUtils;
import com.ledim.utils.ToastUtil;
import com.ledim.widget.view.LoadingBar;
import com.letv.android.young.client.R;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 用户注册页面
 */
public class UserRegisterActivity extends LeDimBaseActivity implements View.OnTouchListener {

    public static final String NEED_LOGIN = "needLogin";
    private TextView mTitle;
    private ImageView mBack;
    private View mPhoneLayout;
    private View mSmsLayout;
    private View mProtocolLayout;
    private View mBigBgLayout;
    private View mTabLayout;
    private View mLine;
    private TextView mPhoneRegister;
    private TextView mSmsRegister;
    private TextView mGetCode;
    private Button mRegister;
    private Button mSend;
    private EditText mMobile;
    private EditText mCode;
    private EditText mPassword;
    private String mPhoneStr;
    private String mCodeStr;
    private String mPasswordStr;
    private TimeCount mTime;
    private TranslateAnimation mAnimation;
    private int mWidth;
    private int mStart;
    /*获取验证码**/
    public static final int TOTAL_DURATION = 60000;
    public static final int INTERVAL = 1000;

    private LoadingBar mLoading;

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_user_register;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    private void initView() {
        mBack = (ImageView) findViewById(R.id.user_top_view_back);
        mTitle = (TextView) findViewById(R.id.user_top_view_title);
        mPhoneLayout = findViewById(R.id.layout_register_phone);
        mSmsLayout = findViewById(R.id.layout_register_sms);
        mProtocolLayout = findViewById(R.id.letv_protocol);
        mBigBgLayout = findViewById(R.id.user_register_bg_layout);
        mTabLayout = findViewById(R.id.user_register_tab_layout);
        mLine = findViewById(R.id.user_register_tab_line);

        mPhoneRegister = (TextView) findViewById(R.id.user_register_phone);
        mSmsRegister = (TextView) findViewById(R.id.user_register_sms);
        mGetCode = (TextView) findViewById(R.id.user_register_getcode);
        mRegister = (Button) findViewById(R.id.user_register_btn);
        mSend = (Button) findViewById(R.id.user_register_send_btn);
        mMobile = (EditText) findViewById(R.id.user_register_mobile);
        mCode = (EditText) findViewById(R.id.user_register_code);
        mPassword = (EditText) findViewById(R.id.user_register_password);

        mBack.setOnClickListener(this);
        mPhoneRegister.setOnClickListener(this);
        mSmsRegister.setOnClickListener(this);
        mGetCode.setOnClickListener(this);
        mRegister.setOnClickListener(this);
        mSend.setOnClickListener(this);
        mProtocolLayout.setOnClickListener(this);
        mBigBgLayout.setOnTouchListener(this);

        mPhoneLayout.setVisibility(View.VISIBLE);
        mSmsLayout.setVisibility(View.GONE);
        mSend.setVisibility(View.GONE);
        mTitle.setText("注册");
        mTitle.setVisibility(View.VISIBLE);

        ViewTreeObserver vto_one = mTabLayout.getViewTreeObserver();
        vto_one.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            public boolean onPreDraw() {
                int width = mTabLayout.getMeasuredWidth();
                mWidth = width / 5;
                return true;
            }
        });
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.user_top_view_back:
                finish();
                break;
            case R.id.user_register_phone:
                mPhoneLayout.setVisibility(View.VISIBLE);
                mSmsLayout.setVisibility(View.GONE);
                mRegister.setVisibility(View.VISIBLE);
                mSend.setVisibility(View.GONE);
                mPhoneRegister.setTextColor(Color.parseColor("#333333"));
                mSmsRegister.setTextColor(Color.parseColor("#999999"));
                mAnimation = new TranslateAnimation(mStart, 0, 0, 0);
                mAnimation.setDuration(300);
                mAnimation.setFillEnabled(true);
                mAnimation.setFillAfter(true);
                mLine.startAnimation(mAnimation);
                mStart = 0;
                break;
            case R.id.user_register_sms:
                mPhoneLayout.setVisibility(View.GONE);
                mSmsLayout.setVisibility(View.VISIBLE);
                mRegister.setVisibility(View.GONE);
                mSend.setVisibility(View.VISIBLE);
                mPhoneRegister.setTextColor(Color.parseColor("#999999"));
                mSmsRegister.setTextColor(Color.parseColor("#333333"));
                mAnimation = new TranslateAnimation(mStart, mWidth * 2, 0, 0);
                mAnimation.setDuration(300);
                mAnimation.setFillEnabled(true);
                mAnimation.setFillAfter(true);
                mLine.startAnimation(mAnimation);
                mStart = mWidth * 2;
                break;
            case R.id.user_register_getcode:
                mPhoneStr = mMobile.getText().toString().trim();
                if (mPhoneStr == null || mPhoneStr.length() == 0) {
                    ToastUtil.toast("请输入手机号");
                    mMobile.requestFocus();
                } else if (!LedimBaseUtils.isMobile(mPhoneStr)) {
                    ToastUtil.toast("请输入正确的手机号");
                    mMobile.requestFocus();
                } else {
                    //获取验证码
                    getCode(mPhoneStr);
                }
                break;
            case R.id.user_register_btn:
                if (LedimNetWorkUtils.isNetworkAvailable(this)) {
                    verifyContent();
                } else {
                    ToastUtil.toast(R.string.net_error);
                }
                break;
            case R.id.user_register_send_btn:
                intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:1069032901305788"));
                intent.putExtra("sms_body", "");
                startActivity(intent);
                break;
            case R.id.letv_protocol:
                LedimFunctionUtils.gotoWebView("http://sso.letv.com/user/protocol?sf=1&sc=0", "乐视服务使用协议", this);
                break;
        }
    }

    private void verifyContent() {
        mPhoneStr = mMobile.getText().toString().trim();
        mPasswordStr = mPassword.getText().toString().trim();
        mCodeStr = mCode.getText().toString().trim();
        if (mPhoneStr == null || mPhoneStr.length() == 0) {
            ToastUtil.toast("请输入手机号");
            mMobile.requestFocus();
        } else if (!LedimBaseUtils.isMobile(mPhoneStr)) {
            ToastUtil.toast("请输入正确的手机号");
            mMobile.requestFocus();
        } else if (mCodeStr == null || mCodeStr.length() == 0) {
            ToastUtil.toast("请输入验证码");
            mCode.requestFocus();
        } else if (mCodeStr.length() < 4) {
            ToastUtil.toast("请输入至少四位验证码");
            mCode.requestFocus();
        } else if (mPasswordStr == null || mPasswordStr.length() == 0) {
            ToastUtil.toast("请输入密码");
            mPassword.requestFocus();
        } else if (mPasswordStr.matches("^[\\u4e00-\\u9fa5]+$")) {
            ToastUtil.toast("密码是6-16位的数字/字母/符号");
            mPassword.requestFocus();
        } else if (mPasswordStr.length() < 6 || mPasswordStr.length() > 16) {
            ToastUtil.toast("密码是6-16位的数字/字母/符号");
            mPassword.requestFocus();
        } else {
            //用户注册
            userRegister(mPhoneStr, null, mPasswordStr, mCodeStr);
        }
    }

    //触摸全屏键盘退出
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        closeKeyBoard();
        return false;
    }

    /**
     * 定义一个倒计时的内部类
     */
    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            mGetCode.setText("重新发送");
            mGetCode.setBackgroundResource(R.drawable.rect_round_code_yellow);
            mGetCode.setClickable(true);
            mGetCode.requestFocus();
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            mGetCode.setText("已发送(" + millisUntilFinished / INTERVAL + ")");
        }
    }

    /**
     * 关闭键盘
     */
    public void closeKeyBoard() {
        mMobile.clearFocus();
        InputMethodManager imm =
                (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mMobile.getWindowToken(), 0);
    }

    /**
     * 用户登录
     */
    private void userLogin(String loginname, String password, String lon, String lat) {
        LedimApiServiceFactory.createService(ApiService.class)
                              .userLogin(loginname, password, LeDimApplication.getDeviceId(UserRegisterActivity.this), lon, lat)
                              .observeOn(AndroidSchedulers.mainThread())
                              .subscribeOn(Schedulers.io())
                              .subscribe(new LedimHttpObserver<LoginResponseBean>() {
                                 @Override
                                 public void onCompleted() {
                                     super.onCompleted();
                                 }

                                 @Override
                                 public void onError(Throwable e) {
                                     super.onError(e);
                                     ToastUtil.toast(e.getMessage());
                                 }

                                 @Override
                                 public void onNext(LoginResponseBean loginResponse) {
                                     super.onNext(loginResponse);
                                     if (loginResponse != null) {
                                         if (loginResponse.success) {
                                             LedimSpUtils.setToken(loginResponse.data.token);
                                             LedimSpUtils.setLetvId(loginResponse.ext.letvid);
                                             LedimSpUtils.setUid(loginResponse.ext.userId);
                                             LedimSpUtils.setLogin(true);

                                             setResult(UserLoginActivity.REGISTER_RESPONSE_CODE);
                                             finish();
                                             Intent intent =
                                                     new Intent(UserRegisterActivity.this, MainActivity.class);
                                             intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                             startActivity(intent);
                                         } else {
                                             //登录失败
                                             ToastUtil.toast(loginResponse.message);
                                         }
                                     }
                                 }
                             });
    }

    /**
     * 用户注册
     *
     * @param mobile
     * @param email
     * @param password
     * @param code
     */
    private void userRegister(String mobile, String email, String password, String code) {

        if (mLoading == null) {
            mLoading = new LoadingBar(this);
        }
        mLoading.show();
        LedimApiServiceFactory.createService(ApiService.class)
                              .userRegister(mobile, email, password, code)
                              .observeOn(AndroidSchedulers.mainThread())
                              .subscribeOn(Schedulers.io())
                              .subscribe(new LedimHttpObserver<BaseResultInfo>() {
                                 @Override
                                 public void onCompleted() {
                                     super.onCompleted();
                                 }

                                 @Override
                                 public void onError(Throwable e) {
                                     super.onError(e);
                                     mLoading.dismiss();
                                     ToastUtil.toast(e.getMessage());
                                 }

                                 @Override
                                 public void onNext(BaseResultInfo data) {
                                     super.onNext(data);
                                     mLoading.dismiss();
                                     if (data != null) {
                                         if (data.success) {
                                             LedimSpUtils.setLogin(true);
                                             ToastUtil.toast("注册成功");
                                             //用户登录
                                             userLogin(mPhoneStr, mPasswordStr, "0", "0");
                                         } else {
                                             //登录失败
                                             ToastUtil.toast(data.message);
                                         }
                                     }
                                 }
                             });
    }

    /**
     * 获取手机验证码
     *
     * @param mobile
     */
    private void getCode(String mobile) {
        if (mLoading == null) {
            mLoading = new LoadingBar(this);
        }
        mLoading.show();
        LedimApiServiceFactory.createService(ApiService.class)
                              .getCode(mobile)
                              .observeOn(AndroidSchedulers.mainThread())
                              .subscribeOn(Schedulers.io())
                              .subscribe(new LedimHttpObserver<BaseResultInfo>() {
                                 @Override
                                 public void onCompleted() {
                                     super.onCompleted();
                                 }

                                 @Override
                                 public void onError(Throwable e) {
                                     super.onError(e);
                                     mLoading.dismiss();
                                     ToastUtil.toast(e.getMessage());
                                 }

                                 @Override
                                 public void onNext(BaseResultInfo data) {
                                     super.onNext(data);
                                     mLoading.dismiss();
                                     if (data != null) {
                                         if (data.success) {
                                             ToastUtil.toast("已发送");
                                             mGetCode.setBackgroundResource(R.drawable.rect_round_code_gray);
                                             mGetCode.setClickable(false);
                                             mTime =
                                                     new TimeCount(TOTAL_DURATION, INTERVAL);// 构造CountDownTimer对象
                                             mTime.start();
                                         } else {
                                             //登录失败
                                             ToastUtil.toast(data.message);
                                         }
                                     }
                                 }
                             });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLoading != null) {
            mLoading.dismiss();
        }
    }
}
